package com.coffee.rocketmq;

import org.apache.rocketmq.spring.support.DefaultRocketMQListenerContainer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.util.StringUtils;

/**
 * @author songkui
 * @since 2024/2/27 10:30
 */
@Configuration
public class EnvironmentProcessor implements BeanPostProcessor {
    @Value("${rocketmq.enhance.isolation:false}")
    private boolean isolation;
    @Value("${rocketmq.enhance.environment:''}")
    private String environmentName;

    @Override
    public Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {
        if (isolation && StringUtils.hasLength(environmentName) && bean instanceof DefaultRocketMQListenerContainer) {
            DefaultRocketMQListenerContainer container = (DefaultRocketMQListenerContainer) bean;
            if (StringUtils.hasText(environmentName)) {
                container.setTopic(String.join("_", container.getTopic(), environmentName));
            }
            return container;
        }
        return bean;
    }


    public String topic(String topic) {
        return String.join("_", topic, environmentName);
    }

    public String destination(String topic, String tag) {
        return topic(topic) + ":" + tag;
    }


}
